const gm = require('gm');
const async = require('async');
const fs = require('fs');
const http = require('http');
const https = require('https');
const path = require('path');
const Grid = require('gridfs-stream');
const mongo = require('mongodb');
const stream = require('stream');

let requestPic=function (url,path,callback){
  if(url.toUpperCase().indexOf("HTTPS")===0){
    https.get(url, (respose)=>{
      let datas = [];
      let size = 0;
      respose.on('data', function (data) {
        datas.push(data);
        size += data.length;
      });
      respose.on("end", function () {
        let buff = Buffer.concat(datas, size);
        gm(buff)
            .write(path, callback);
      });
    }).on("error", function (err) {
      console.log(err);
    });
  }
  else{
    http.get(url, (respose)=>{
      let datas = [];
      let size = 0;
      respose.on('data', function (data) {
        datas.push(data);
        size += data.length;
      });
      respose.on("end", function () {
        let buff = Buffer.concat(datas, size);
        gm(buff)
            .write(path, callback);
      });
    }).on("error", function (err) {
      console.log(err);
    });
  }
};
module.exports = {
  handler(req,res,next){
    let doc = req.query;
    let cardID = doc.filter.cardID;
    req.mongo.collection("card").find({"_id":cardID}).next((e,r)=>{
      if(e) return res.err.mongoError(e);
      if(r.makedPicPath){
        return res.reply({code:2000,msg:"该图片已合成过，路径为："+r.makedPicPath+",不需要再次合成！",url:r.makedPicPath})
      }else{
        let str = r.title;
        let nickname = r.nickname;
        let headPicPath = r.headPicPath;
        let userID = r.authorID;
        let picturePath = r.picPath;

        let qrcodePath = r.qrcodePath||"http://sl.huiwanvip.com/5e20192e19e6ef584f78aad2/content.png";

        //将输入的长度为40以内的文本，先补足空格，再以每行20的长度进行折行
        let length =40-str.length;
        for(let i =0;i<length;i++){
          str = str + " ";//补足空格
        }
        let strArr = [];
        let n = 20;
        for (let i = 0, l = str.length; i < l/n; i++) {
          let a = str.slice(n*i, n*(i+1));
          strArr.push(a);
        }

        async.auto([
          callback=>requestPic(headPicPath,userID+"headPic.png",callback),
          callback=>requestPic(picturePath,userID+"picture.png",callback),
          callback=>requestPic(qrcodePath,userID+"qrcode.png",callback)
        ],(e,r)=>{
          if(e) return console.log(e);
          // gm(717,1002,"#ffffff")
          gm(1075,1480,"#ffffff")
              .draw("image Over 0, 0, 1075, 1480 "+path.join(__dirname,"/bg.jpg"))
              .draw("image Over 49, 113, 123, 123 '"+userID+"headPic.png'")
              // .draw("image Over 36, 353, 1000, 750 '"+userID+"picture.png'")
              .draw("image Over 55, 353, 965, 750 '"+userID+"picture.png'")
              .draw("image Over 75, 1203, 162, 162 '"+userID+"qrcode.png'")
              // .draw("image Over 291, 1261, 684, 49 "+path.join(__dirname,"/bottom.png"))

              .fill("black")
              .font("苹方粗体",45)
              // .draw("text 203,80 '"+nickname+"'")
              .draw("text 203,154 '"+nickname+"'")

              .fill("black")
              .font("苹方",39)
              // .draw("text 203,137 '"+strArr[0]+"'")
              .draw("text 203,211 '"+strArr[0]+"'")

              .fill("black")
              .font("苹方",39)
              // .draw("text 203,189 '"+strArr[1]+"'")
              .draw("text 203,263 '"+strArr[1]+"'")

              //为了控制最终图片的输出大小，将后缀名改为JPEG
              .write(path.join(__dirname,"./../../../../static/sharePic/"+cardID+".JPEG"), function (error,result) {
                if(error) console.log(error);
                fs.unlink(userID+"headPic.png", ()=>{});//删除文件
                fs.unlink(userID+"picture.png", ()=>{});
                fs.unlink(userID+"qrcode.png", ()=>{});

                  const url = req.config.sys.resHost+ '/static/sharePic/' + cardID+".JPEG";
                  const fileObj = {
                                  _id: cardID,
                                  filename: cardID+".JPEG",
                                  url: url,
                                  createTime:new Date(),
                                  code:0
                              };

                  req.mongo.collection("card").updateOne({"_id":cardID},{$set:{"makedPicPath":fileObj.url}},{upsert:true},(e3,r3)=>{
                      if(e3) return res.err.mongoError(e3);
                      res.reply(fileObj);
                  });
                //const id = new mongo.ObjectID();
                //fs.readFile(path.join(__dirname,"/"+userID+"card.JPEG"),(err,originBuffer)=>{
                //    const buffer = new Buffer(originBuffer, "base64");
                //    const qiniu = require('yi-qiniu');
                //    qiniu.uploadBuffer(buffer,userID+"card.JPEG",(e,r)=>{
                //        if(e)
                //        {
                //            return res.err.unknownError(e);
                //        }
                //        const fileObj = {
                //            _id: id,
                //            filename: userID+"card.JPEG",
                //            url: r.url,
                //            createTime:new Date(),
                //            hash: r.hash,
                //            code:0
                //        };
                //        res.reply(fileObj);
                //        req.mongo.collection("file").insertOne(fileObj,(e,r)=>{
                //          fs.unlink(path.join(__dirname,"/"+userID+"card.JPEG"), ()=>{});
                //          if(e) return res.err.mongoError(e);
                //          req.mongo.collection("card").updateOne({"_id":cardID},{$set:{"makedPicPath":fileObj.url}},{upsert:true})
                //        });
                //    },id.toString());
                //})
              });
        })
      }
    })
  }
};